package com.tools.sys.controller;

import com.alibaba.nacos.common.utils.Md5Utils;
import com.tools.cache.util.RedisUtils;
import com.tools.common.core.model.Result;
import com.tools.common.core.util.JwtUtils;
import com.tools.sys.entity.SysUser;
import com.tools.sys.service.GirlFeignService;
import com.tools.sys.service.SysUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 登录
 * 爪哇笔记：https://blog.52itstyle.vip
 */
@Api(tags ="登录")
@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(String username,String password) {
        try {
            SysUser user = sysUserService.getUser(username);
            if (user != null) {
                if (!user.getPassword().equals(Md5Utils.getMD5(password, "utf-8"))) {
                    return Result.error("密码不正确");
                } else {
                    List<Object> permsList =
                            sysUserService.listUserPerms(user.getUserId());
                    redisUtils.lSetAll("perms:" + user.getUserId(), permsList);
                    List<Object> rolesList =
                            sysUserService.listUserRoles(user.getUserId());
                    redisUtils.lSetAll("roles:" + user.getUserId(), rolesList);
                    String token =
                            JwtUtils.createJWT(user.getUserId().toString(), user.getNickname());
                    return Result.ok(token);
                }
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("登录失败");
        }

    }
    @Autowired
    private GirlFeignService meiziFeignService;

    @RequestMapping("/getMeiZi")
    public String getMeiZi(){
        return meiziFeignService.getMeiZi(1L);
    }

    public static void main(String[] args) {
        System.out.println(Md5Utils.getMD5("6347097","utf-8"));
    }
}
